import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_libserialport/flutter_libserialport.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../entity/setting_entity.dart';
import '../main.dart';
import '../util/toast_util.dart';


class SettingCommon extends StatefulWidget {
  const SettingCommon({Key? key}) : super(key: key);

  @override
  State<SettingCommon> createState() => _SettingCommonState();
}

class _SettingCommonState extends State<SettingCommon>  {

  StreamSubscription? actionSubscription;
  SettingEntity? entity;
  final box = GetStorage();

  var _apiAddr = "192.168.2.100";

  var _deviceName = "轩毅";
  // var _publishName = "轩毅";
  var _deviceNo = "device_id=test";
  final _port = "/dev/ttyS1".obs;

  Set<String> data = {};

  @override
  initState() {
    super.initState();
    // box.remove("setting_entity");
    if(box.hasData('setting_entity')){
      entity = SettingEntity.fromJson(box.read("setting_entity"));

      if(entity!.apiAddr != null){
        _apiAddr = entity!.apiAddr!;
      }
      if(entity!.deviceName != null){
        _deviceName = entity!.deviceName!;
      }
      if(entity!.port != null){
        _port.value = entity!.port!;
      }
      if(entity!.deviceNo != null){
        _deviceNo = entity!.deviceNo!;
      }
      if(entity!.isUltra != null){
        isUltra.value = entity!.isUltra!;
      }

    }else{
      entity = SettingEntity();
    }
  }

  _apiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备名 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceName = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceName,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceName.length))
            )),
          ),
        ),

        Text("  api地址 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _apiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _apiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _apiAddr.length))
            )),
          ),
        ),
      ],
    );
  }

  RxBool isUltra = RxBool(false);


  // _readerWidget(){
  //   return Row(
  //     mainAxisAlignment: MainAxisAlignment.start,
  //     children: [
  //       Text("  高频",   style: TextStyle(fontSize: 8.sp),),
  //       Obx(() => Switch(
  //           value: isUltra.value,
  //           onChanged: (value) {
  //             isUltra.value = value;
  //           }
  //       ),),
  //       Text("超高频    ",   style: TextStyle(fontSize: 8.sp),),
  //     ],
  //   );
  // }
  //
  //

  _deviceNoWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备号",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceNo,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceNo.length))
            )),
          ),
        ),
        TextButton(onPressed: () {
          _saveDevice();
        }, child: Text('保存配置',   style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }

  _serialWidget(){
    List<String> availablePorts = SerialPort.availablePorts;
    var items = availablePorts.map((e) => DropdownMenuItem(value:e, child:Text(e))).toList();
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  读写器  ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5.r),
          child: Obx(() => DropdownButton(
            value: _port.value,
            onChanged: (value){
              _port.value = value.toString();
            },
            items: items,
          )),
        ),
      ],
    );
  }

  _saveDevice(){
    entity!.deviceNo = _deviceNo;
    entity!.apiAddr = _apiAddr;
    entity!.port = _port.value;
    entity!.deviceName = _deviceName;
    entity!.isUltra = isUltra.value;
    box.write('setting_entity', entity!.toJson());
    toastWarn('保存成功');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("配置"),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: (){

            if(box.hasData('setting_entity')){
              settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
            }
            Get.back();
          },
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _deviceNoWidget(),
          _apiWidget(),
          _serialWidget(),
          // _actionWidget()
        ],
      ),
    );
  }
}

